import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useTokenStore } from '@/stores/token.js'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    //直接跳到后台登录页面
    { path: '/', redirect: '/login' },
    {
      path: '/login',
      name: 'login',
      meta: { title: '管理端登录页面' },
      component: () => import('@/views/Login.vue')
    },
    {
      path: '/list',
      name: 'reportList',
      component: () => import('@/views/list.vue'),
      meta: {
        requiresAuth: true
      },
      // 添加子路由，处理不同角色的访问
      children: [
        {
          path: '',
          name: 'reportListHome',
          component: () => import('@/views/list.vue')
        }
      ]
    },
    {
      path: '/detail/:reportId',
      name: 'reportDetail',
      component: () => import('@/views/detail.vue'),
      meta: { requiresAuth: true }
    }
  ]
})

// 添加全局前置守卫，处理权限验证和角色路由
router.beforeEach((to, from, next) => {
  // 需要登录的页面进行校验
  const tokenStore = useTokenStore()
  
  // 判断是否需要登录权限
  if (to.meta.requiresAuth) {
    // 检查是否有token
    if (!tokenStore.token) {
      ElMessage.warning('请先登录')
      next({ path: '/login' })
      return
    }
  }

  // 如果是登录页面且已有token，直接跳转到列表页
  if (to.path === '/login' && tokenStore.token) {
    next({ path: '/list' })
    return
  }

  // 处理带有角色参数的路由
  if (to.path === '/list' && to.query.role !== undefined) {
    // 角色存在，允许访问
    next()
  } else {
    next()
  }
})

//导出路由
export default router 